package ug.co.icom.kyazze.healthticket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import ug.co.icom.kyazze.healthticket.data.Allergy;
import android.os.AsyncTask;

public class MongoHQDataAccess extends AsyncTask<String, Void, ArrayList<Allergy>> {

	static BasicDBList allergies = null;
	static String OriginalObject = "";
	static String server_output = null;
	static String temp_output = null;
	static ArrayList<Allergy> phr_allergies = new ArrayList<Allergy>();
	
	@SuppressWarnings("deprecation")
	@Override
	protected ArrayList<Allergy> doInBackground(String... params) {
		try {
			URL url = new URL(
					"https://api.mongohq.com/databases/mHealth/collections/medical_records/documents?_apikey=YPXfSPrBkC5EMptf7m6pxSlB3B2AcRUc6Mk7mWuPO0&limit=5");
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			System.out.println("Output from Server .... \n");
			while ((temp_output = br.readLine()) != null) {
				server_output = temp_output;
			}

			// Remove square brackets
			OriginalObject = server_output.substring(1, server_output.length() - 1);

			Object o = com.mongodb.util.JSON.parse(OriginalObject);

			DBObject dbObj = (DBObject) o;
			allergies = (BasicDBList) dbObj.get("allergies");

			Allergy temp = new Allergy();

			for (Object obj : allergies) {

				BasicDBObject healthObj = (BasicDBObject) obj;

				temp.Name = healthObj.get("name").toString();
				temp.DateOfDiagnosis = new Date(healthObj.get("date_of_diagnosis")
						.toString());
				temp.Severity = healthObj.get("reaction").toString();
				temp.Reaction = healthObj.get("reaction").toString();
				temp.Occurrence = healthObj.get("occurence").toString();
				temp.Name = healthObj.get("name").toString();
				temp.Comments = healthObj.get(
						"additional_comments").toString();

				phr_allergies.add(temp);

			}

			
		}catch (Exception e) {
			e.printStackTrace();
		}

		return phr_allergies;
	}

	@Override
	protected void onPostExecute(ArrayList<Allergy> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
	}
}
